<?php

namespace App\Console\Commands\Article;

use App\Models\Article\ArticleModel;
use App\Models\Article\ArticleStatisticsDayModel;
use App\Service\Article\ArticleOperateService;
use Illuminate\Console\Command;

class ArticleStatisticsHot extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'article:statistics_hot_script';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '文章数据统计-热门文章数据每小时落库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $startTime = strtotime(date('Y-m-d'));//当天时间
        $createdAt = time();

        //查询单个文章的  4:阅读数
        self::totalArticleStatistics($startTime, $createdAt);

    }


    /**
     * 文章的阅读数 数据统计
     * @param $startTime
     * @param $createdAt
     */
    public function totalArticleStatistics($startTime, $createdAt)
    {
        $day            = date('Ymd', $startTime);
        $batchTotalData = [];
        ArticleModel::query()
//            ->where('status', ArticleModel::STATUS_ON)
            ->whereIn("publishType", array_keys(ArticleModel::PUBLISH_NO_DRAFT_TYPE_TEXT))
            ->chunkById(
                100, function ($item) use ($startTime, $createdAt, $day, &$batchTotalData) {
                $articleIds            = collect($item)->pluck('id')->unique()->toArray();
                $articleStatisticsList = ArticleStatisticsDayModel::query()
                    ->where('dateAt', $startTime)
                    ->where('source', ArticleStatisticsDayModel::TYPE_READ)
                    ->whereIn('articleId', $articleIds)
                    ->get()->keyBy('articleId')->toArray();

                foreach ($item as $v) {
                    $totalRedisData = ArticleOperateService::getTotalArticleRedisData($day, $v->id);
                    $this->info("debug date:" . $day . ' id:' . $v->id . ' ' . json_encode($totalRedisData));

                    if ($totalRedisData['readNum']) {
                        if (isset($articleStatisticsList[$v->id])) {
                            if ($articleStatisticsList[$v->id]['newNum'] != $totalRedisData['readNum']) {
                                ArticleStatisticsDayModel::query()
                                    ->where('id', $articleStatisticsList[$v->id]['id'])
                                    ->update(['newNum' => $totalRedisData['readNum']]);
                            }
                            continue;
                        }

                        $batchTotalData[] = [
                            'dateAt'      => $startTime,                                                                              //统计日
                            'articleId'   => $v->id,                                                                                  //文章 ID, 0为所有
                            'source'      => ArticleStatisticsDayModel::TYPE_READ,                                                    //数据来源 1: 点赞数, 2:收藏数 3:转发数 4:阅读数 5:展示数
                            'cumulateNum' => 0,                                                                                       //累计
                            'newNum'      => $totalRedisData['readNum'],                                                              //新增
                            'cancelNum'   => 0,                                                                                       //取消
                            'netIncNum'   => $totalRedisData['readNum'],                                                              //净增
                            'createdAt'   => $createdAt,
                        ];
                    }
                }
            }
            );

        if ($batchTotalData) {
            ArticleStatisticsDayModel::batchInsertData($batchTotalData);
        }

    }
}
